// app.js
// 在文件顶部引入 dotenv 配置
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const userRoutes = require('./routes/userRoutes');
const authRoutes = require('./routes/authRoutes');
const productRoutes = require('./routes/productRoutes');

const uploadRoutes = require('./routes/uploadRoutes'); // 引入上传路由
const orderRoutes = require('./routes/orderRoutes');

const adminRoutes = require('./routes/adminRoutes');
const groupbuyRoutes = require('./routes/groupbuyRoutes');

const app = express();
const PORT = 3001;
// 中间件
app.use(cors());
app.use(express.json());  // 解析 JSON 数据
app.use(express.urlencoded({ extended: true }));  // 解析 URL 编码的数据

app.use('/uploads', express.static('public/uploads')); // 配置上传文件存储路径
// 配置路由
app.use('/api', productRoutes);  // 这样 /api/products 就能匹配到了
app.use('/api/admin', adminRoutes);
app.use('/api', userRoutes);
app.use('/api/auth', authRoutes);
app.use('/api', uploadRoutes); // 图片上传路由
app.use('/api', orderRoutes);
app.use('/api', groupbuyRoutes);

// 在所有路由之后添加错误处理中间件
app.use((err, req, res, next) => {
    console.error('服务器错误:', err.stack);
    res.status(500).json({
        code: 500,
        message: '服务器内部错误',
        error: process.env.NODE_ENV === 'development' ? err.message : undefined
    });
});

// 处理 404
app.use((req, res) => {
    console.log('404 Not Found:', req.method, req.url);
    res.status(404).json({
        code: 404,
        message: '请求的资源不存在'
    });
});

// 启动服务器
app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});

module.exports = app;
